//
//  EditPDFView.m
//  PDFKitTest
//
//  Created by Emo, on 2024/1/23.
//

#import "EditPDFView.h"
#import "PKPDFView.h"

@interface EditPDFView () <PDFViewDelegate, PDFDocumentDelegate>

@property (nonatomic, strong) UILabel * indicatorLabel;

@end

@implementation EditPDFView

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupUI];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    // 展示PDF视图
    self.pdfView = [[PKPDFView alloc] initWithFrame:self.bounds];
    self.pdfView.pageBreakMargins = UIEdgeInsetsMake(10, 10, 10, 10);
    self.pdfView.delegate = self;
    self.pdfView.autoScales = YES;
    [self addSubview:self.pdfView];
    // 指示器
    self.indicatorLabel = [[UILabel alloc] init];
    self.indicatorLabel.frame = CGRectMake(30, self.frame.size.height-50, 70, 30);
    self.indicatorLabel.layer.cornerRadius = 5;
    self.indicatorLabel.layer.masksToBounds = YES;
    self.indicatorLabel.font = [UIFont systemFontOfSize:15];
    self.indicatorLabel.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.3f];
    self.indicatorLabel.textColor = [UIColor whiteColor];
    self.indicatorLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.indicatorLabel];
    // 绘图
    
    
    // 添加监听
    [self addObservers];
}


#pragma mark -- observer --
- (void)addObservers {
    
    kWeakSelf;
    [[NSNotificationCenter defaultCenter] addObserverForName:PDFViewPageChangedNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        weakSelf.indicatorLabel.text = [NSString stringWithFormat:@"%ld / %ld", [self getCurrentPageIndex], [self getTotalPageCount]];
    }];
}

#pragma mark -- getter && setter --
- (void)setLocalPDFPath:(NSString *)localPDFPath {
    _localPDFPath = localPDFPath;
    if (localPDFPath.length > 0) {
        PDFDocument *document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:localPDFPath]];
        self.pdfView.document = document;
    }
}




#pragma mark -- function --
/** 获取当前PDF页面下标*/
- (NSInteger)getCurrentPageIndex {
    return self.pdfView.currentPage.label.integerValue;
}
/** 获取PDF总页数*/
- (NSInteger)getTotalPageCount {
    return self.pdfView.document.pageCount;
}
/** 保存文件到指定路径*/
- (void)saveToFile:(NSString *)path block:(void(^)(BOOL success))block {
    BOOL success = NO;
    NSData *data = self.pdfView.document.dataRepresentation;
    if (data) {
        success = [data writeToFile:path atomically:YES];
    }
    if (block) {
        block(success);
    }
}

#pragma mark -- dealloc --
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
